package com.emotion.sshticket.controllers;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emotion.sshticket.mail.MailUtil;
import com.emotion.sshticket.services.FrontService;
import com.emotion.sshticket.utilitys.ValueUtil;
import com.emotion.sshticket.vo.TicketVO;

@Controller
public class FrontController {
	@Resource(name="messageSource")
	private MessageSource messageSource;

	@Resource(name="propertySource")
	private Properties propertySource;

	@Resource(name="frontService")
	private FrontService frontService;

	@RequestMapping("/index.do")
	public ModelAndView loginForm(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		try {
			// 메인 페이지 노출
			mv.setViewName("index");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/ticketForm.do")
	public ModelAndView ticketForm(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		try {
			int ticketMaxLimit = Integer.parseInt(propertySource.getProperty("limit.max.ticket"));
			int ticketPrice = Integer.parseInt(propertySource.getProperty("price.ticket"));
			int deliveryPrice = Integer.parseInt(propertySource.getProperty("price.delivery"));

			mv.addObject("ticketPrice", ticketPrice);
			mv.addObject("deliveryPrice", deliveryPrice);
			mv.addObject("ticketMaxLimit", ticketMaxLimit);
			mv.setViewName("ticketForm");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/purchaseForm.do")
	public ModelAndView purchaseForm(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		try {
			String userNameF =		ValueUtil.nullToString(request.getParameter("userNameF"));
			String userNameS =		ValueUtil.nullToString(request.getParameter("userNameS"));
			String hiraganaF =		ValueUtil.nullToString(request.getParameter("hiraganaF"));
			String hiraganaS =		ValueUtil.nullToString(request.getParameter("hiraganaS"));
			String userId =			ValueUtil.nullToString(request.getParameter("userId"));
			String userEmail =		ValueUtil.nullToString(request.getParameter("userEmail"));
			String userEmail1_1 =	ValueUtil.nullToString(request.getParameter("userEmail1_1"));
			String userEmail1_2 =	ValueUtil.nullToString(request.getParameter("userEmail1_2"));
			String userEmail2_1 =	ValueUtil.nullToString(request.getParameter("userEmail2_1"));
			String userEmail2_2 =	ValueUtil.nullToString(request.getParameter("userEmail2_2"));
			String postAdd =		ValueUtil.nullToString(request.getParameter("postAdd"));
			String postAdd1 =		ValueUtil.nullToString(request.getParameter("postAdd1"));
			String postAdd2 =		ValueUtil.nullToString(request.getParameter("postAdd2"));
			String addr1 =			ValueUtil.nullToString(request.getParameter("addr1"));
			String addr2 =			ValueUtil.nullToString(request.getParameter("addr2"));
			String addr3 =			ValueUtil.nullToString(request.getParameter("addr3"));
			int onceTicket =		ValueUtil.nullToInt(request.getParameter("onceTicket"));
			int twiceTicket =		ValueUtil.nullToInt(request.getParameter("twiceTicket"));
			String phone =			ValueUtil.nullToString(request.getParameter("phone"));
			String phone1 =			ValueUtil.nullToString(request.getParameter("phone1"));
			String phone2 =			ValueUtil.nullToString(request.getParameter("phone2"));
			String phone3 =			ValueUtil.nullToString(request.getParameter("phone3"));

			int ticketPrice = Integer.parseInt(propertySource.getProperty("price.ticket"));
			int deliveryPrice = Integer.parseInt(propertySource.getProperty("price.delivery"));

			if (onceTicket + twiceTicket == 0) {
				throw new Exception("error.ticker.nonselected");
			}

			TicketVO ticketVO = new TicketVO();
			ticketVO.setUserId(userId);
			ticketVO.setUserEmail(userEmail);
			ticketVO.setUserNameF(userNameF);
			ticketVO.setUserNameS(userNameS);
			ticketVO.setHiraganaF(hiraganaF);
			ticketVO.setHiraganaS(hiraganaS);
			ticketVO.setPostAdd(postAdd);
			ticketVO.setAddr1(addr1);
			ticketVO.setAddr2(addr2);
			ticketVO.setAddr3(addr3);
			ticketVO.setPhone(phone);
			ticketVO.setOnceTicket(onceTicket);
			ticketVO.setTwiceTicket(twiceTicket);
			ticketVO.setPrice((onceTicket * ticketPrice) + (twiceTicket * ticketPrice) + deliveryPrice);

			// 상세 구매 정보 입력 폼 호출
			// 이곳에서 중복체크를 하게되면 ajax로 사용자 정보를 확인할 것인가?
			// 크로스 도메인은 무리, 입력된 휴대폰 번호로 검증할 것인가?
			mv.addObject("ticket", ticketVO);
			mv.addObject("addrList", ValueUtil.getAddrList());
			mv.addObject("userEmail1_1", userEmail1_1);
			mv.addObject("userEmail1_2", userEmail1_2);
			mv.addObject("userEmail2_1", userEmail2_1);
			mv.addObject("userEmail2_2", userEmail2_2);
			mv.addObject("postAdd1", postAdd1);
			mv.addObject("postAdd2", postAdd2);
			mv.addObject("phone1", phone1);
			mv.addObject("phone2", phone2);
			mv.addObject("phone3", phone3);
			mv.addObject("ticketPrice", ticketPrice);
			mv.addObject("deliveryPrice", deliveryPrice);
			mv.setViewName("purchaseForm");
		} catch (Exception e) {
			e.printStackTrace();
			mv.addObject("errorMsg", messageSource.getMessage(e.getMessage(), null, "system.error", request.getLocale()));
		}
		return mv;
	}

	@RequestMapping("/checkDuplacate.do")
	@ResponseBody
	public JSONObject checkDuplacate(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			String userEmail =	ValueUtil.nullToString(request.getParameter("userEmail"));

			if (frontService.getCheckDuplacateCount(userEmail) > 0) {
				String message = messageSource.getMessage("error.email.exist", null, request.getLocale());
				throw new Exception(message);
			}

			jsonObject.put("result", "OK");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("errorMsg", e.getMessage());
		}
		return jsonObject;
	}

	@RequestMapping(value="/checkPurchase.do", method=RequestMethod.POST)
	public ModelAndView checkPurchase(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		try {
			String userNameF =		ValueUtil.nullToString(request.getParameter("userNameF"));
			String userNameS =		ValueUtil.nullToString(request.getParameter("userNameS"));
			String hiraganaF =		ValueUtil.nullToString(request.getParameter("hiraganaF"));
			String hiraganaS =		ValueUtil.nullToString(request.getParameter("hiraganaS"));
			String userId =			ValueUtil.nullToString(request.getParameter("userId"));
			String userEmail =		ValueUtil.nullToString(request.getParameter("userEmail"));
			String userEmail1_1 =	ValueUtil.nullToString(request.getParameter("userEmail1_1"));
			String userEmail1_2 =	ValueUtil.nullToString(request.getParameter("userEmail1_2"));
			String userEmail2_1 =	ValueUtil.nullToString(request.getParameter("userEmail2_1"));
			String userEmail2_2 =	ValueUtil.nullToString(request.getParameter("userEmail2_2"));
			String postAdd =		ValueUtil.nullToString(request.getParameter("postAdd"));
			String postAdd1 =		ValueUtil.nullToString(request.getParameter("postAdd1"));
			String postAdd2 =		ValueUtil.nullToString(request.getParameter("postAdd2"));
			String addr1 =			ValueUtil.nullToString(request.getParameter("addr1"));
			String addr2 =			ValueUtil.nullToString(request.getParameter("addr2"));
			String addr3 =			ValueUtil.nullToString(request.getParameter("addr3"));
			int onceTicket =		ValueUtil.nullToInt(request.getParameter("onceTicket"));
			int twiceTicket =		ValueUtil.nullToInt(request.getParameter("twiceTicket"));
			String phone =			ValueUtil.nullToString(request.getParameter("phone"));
			String phone1 =			ValueUtil.nullToString(request.getParameter("phone1"));
			String phone2 =			ValueUtil.nullToString(request.getParameter("phone2"));
			String phone3 =			ValueUtil.nullToString(request.getParameter("phone3"));

			int ticketPrice = Integer.parseInt(propertySource.getProperty("price.ticket"));
			int deliveryPrice = Integer.parseInt(propertySource.getProperty("price.delivery"));

			TicketVO ticketVO = new TicketVO();
			ticketVO.setUserId(userId);
			ticketVO.setUserEmail(userEmail);
			ticketVO.setUserNameF(userNameF);
			ticketVO.setUserNameS(userNameS);
			ticketVO.setHiraganaF(hiraganaF);
			ticketVO.setHiraganaS(hiraganaS);
			ticketVO.setPostAdd(postAdd);
			ticketVO.setAddr1(addr1);
			ticketVO.setAddr2(addr2);
			ticketVO.setAddr3(addr3);
			ticketVO.setPhone(phone);
			ticketVO.setOnceTicket(onceTicket);
			ticketVO.setTwiceTicket(twiceTicket);
			ticketVO.setPrice((onceTicket * ticketPrice) + (twiceTicket * ticketPrice) + deliveryPrice);

			if (frontService.getCheckDuplacateCount(userEmail) > 0) {
				throw new Exception("error.email.exist");
			}

			if (onceTicket + twiceTicket == 0) {
				throw new Exception("error.ticker.nonselected");
			}

			if (userNameF.equals("") || userNameS.equals("") || hiraganaF.equals("") || hiraganaS.equals("")) {
				throw new Exception("error.ticker.nonselected");
			}

			mv.addObject("ticket", ticketVO);
			mv.addObject("userEmail1_1", userEmail1_1);
			mv.addObject("userEmail1_2", userEmail1_2);
			mv.addObject("userEmail2_1", userEmail2_1);
			mv.addObject("userEmail2_2", userEmail2_2);
			mv.addObject("postAdd1", postAdd1);
			mv.addObject("postAdd2", postAdd2);
			mv.addObject("phone1", phone1);
			mv.addObject("phone2", phone2);
			mv.addObject("phone3", phone3);
			// 입력한 정보를 노출
			mv.setViewName("checkPurchase");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/purchase.do")
	@ResponseBody
	public JSONObject purchase(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			String userNameF =	ValueUtil.nullToString(request.getParameter("userNameF"));
			String userNameS =	ValueUtil.nullToString(request.getParameter("userNameS"));
			String hiraganaF =	ValueUtil.nullToString(request.getParameter("hiraganaF"));
			String hiraganaS =	ValueUtil.nullToString(request.getParameter("hiraganaS"));
			String userId =		ValueUtil.nullToString(request.getParameter("userId"));
			String userEmail =	ValueUtil.nullToString(request.getParameter("userEmail"));
			String postAdd =	ValueUtil.nullToString(request.getParameter("postAdd"));
			String addr1 =		ValueUtil.nullToString(request.getParameter("addr1"));
			String addr2 =		ValueUtil.nullToString(request.getParameter("addr2"));
			String addr3 =		ValueUtil.nullToString(request.getParameter("addr3"));
			int onceTicket =	ValueUtil.nullToInt(request.getParameter("onceTicket"));
			int twiceTicket =	ValueUtil.nullToInt(request.getParameter("twiceTicket"));
			String phone =		ValueUtil.nullToString(request.getParameter("phone"));
			int price = 		ValueUtil.nullToInt(request.getParameter("price"));

			int ticketPrice = Integer.parseInt(propertySource.getProperty("price.ticket"));
			int deliveryPrice = Integer.parseInt(propertySource.getProperty("price.delivery"));

			if (price != (onceTicket * ticketPrice) + (twiceTicket * ticketPrice) + deliveryPrice) {
				String message = messageSource.getMessage("error.price", null, request.getLocale());
				throw new Exception(message);
			}

			TicketVO ticketVO = new TicketVO();
			ticketVO.setUserId(userId);
			ticketVO.setUserEmail(userEmail);
			ticketVO.setUserNameF(userNameF);
			ticketVO.setUserNameS(userNameS);
			ticketVO.setHiraganaF(hiraganaF);
			ticketVO.setHiraganaS(hiraganaS);
			ticketVO.setPostAdd(postAdd);
			ticketVO.setAddr1(addr1);
			ticketVO.setAddr2(addr2);
			ticketVO.setAddr3(addr3);
			ticketVO.setPhone(phone);
			ticketVO.setOnceTicket(onceTicket);
			ticketVO.setTwiceTicket(twiceTicket);
			ticketVO.setPrice((onceTicket * ticketPrice) + (twiceTicket * ticketPrice) + deliveryPrice);

			if (frontService.getCheckDuplacateCount(userEmail) > 0) {
				String message = messageSource.getMessage("error.email.exist", null, request.getLocale());
				throw new Exception(message);
			}

			if (userNameF.equals("") || userNameS.equals("") || hiraganaF.equals("") || hiraganaS.equals("") ||
					userEmail.equals("") || postAdd.equals("") || addr1.equals("") || addr2.equals("") || addr3.equals("") ||
					onceTicket + twiceTicket == 0 || phone.equals("")) {
				String message = messageSource.getMessage("error.purchase.input", null, request.getLocale());
				throw new Exception(message);
			}

			frontService.insertTicketingInfo(ticketVO);

			DecimalFormat df = new DecimalFormat("#,##0");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

			String fileName = "/purchaseMail.txt";
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("userName",		ticketVO.getUserNameF() + " " + ticketVO.getUserNameS());
			dataMap.put("phone",		ticketVO.getPhone());
			dataMap.put("registDate",	sdf.format(Calendar.getInstance().getTime()));
			dataMap.put("onceTicket",	ticketVO.getOnceTicket());
			dataMap.put("twiceTicket",	ticketVO.getTwiceTicket());
			dataMap.put("price",		df.format(ticketVO.getPrice()));
			dataMap.put("hiragana",		ticketVO.getHiraganaF() + " " + ticketVO.getHiraganaS());
			dataMap.put("postAdd",		ticketVO.getPostAdd());
			dataMap.put("addr1",		ticketVO.getAddr1());
			dataMap.put("addr2",		ticketVO.getAddr2());
			dataMap.put("addr3",		ticketVO.getAddr3());
			dataMap.put("userEmail",	ticketVO.getUserEmail());
			dataMap.put("userId",		ticketVO.getUserId());
			MailUtil.sendMail(userEmail, fileName, dataMap);

			jsonObject.put("result", "OK");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("errorMsg", e.getMessage());
		}
		return jsonObject;
	}

	@RequestMapping("/purchaseResult.do")
	public ModelAndView purchaseResult(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error");
		try {
			mv.setViewName("purchaseResult");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
}
